package com.xh.rufongwallpaper.aspect;

import com.xh.rufongwallpaper.annotation.Cacheable;
import com.xh.rufongwallpaper.config.CacheProperties;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Aspect
@Component
@RequiredArgsConstructor
@ConditionalOnProperty(name = "spring.redis.enabled", havingValue = "true", matchIfMissing = false)
public class CacheAspect {

    private final RedisTemplate<String, Object> redisTemplate;
    private final CacheProperties cacheProperties;

    @Around("@annotation(cacheable)")
    public Object around(ProceedingJoinPoint point, Cacheable cacheable) throws Throwable {
        if (!cacheProperties.isEnabled()) {
            return point.proceed();
        }

        String key = generateKey(point, cacheable);
        Object value = redisTemplate.opsForValue().get(key);
        if (value != null) {
            return value;
        }

        value = point.proceed();
        long ttl = cacheable.ttl() > 0 ? cacheable.ttl() : cacheProperties.getTtl();
        redisTemplate.opsForValue().set(key, value, ttl, TimeUnit.SECONDS);
        return value;
    }

    private String generateKey(ProceedingJoinPoint point, Cacheable cacheable) {
        String key = cacheable.key();
        if (key.isEmpty()) {
            key = point.getSignature().getDeclaringTypeName() + "." + point.getSignature().getName();
        }
        return key;
    }
} 